package ai.people.platform.archives.ws.extractor;

import ai.people.core.security.extractor.TokenValueExtractor;
import ai.people.netmon.utils.StringPool;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 套接字令牌值器
 *
 * @author yuanqinglong
 * @date 2022/7/11 13:39
 */
@Component
public class SocketTokenValueExtractor implements TokenValueExtractor {


    /**
     * 提取令牌
     *
     * @param request 请求
     * @return {@link String}
     */
    @Override
    public String extractToken(HttpServletRequest request) {
        Enumeration<String> headers = request.getHeaders("Sec-WebSocket-Protocol");
        while (headers.hasMoreElements()) {
            String value = headers.nextElement();
            if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
                String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
                request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,
                        value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim());
                int commaIndex = authHeaderValue.indexOf(StringPool.COMMA);
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                return authHeaderValue;
            }
        }
        return null;
    }

}
